package deng.hibernate.examples.employees.cli;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;

import deng.hibernate.examples.employees.Employee;

public class EmployeesJPA extends EmployeesEntityManager {

	public static void main(String[] args) {
		new EmployeesJPA().run();
	}

	@Override
	protected void runTxExample(EntityManager em) {
//		persistEmployee(em, createEmployee());
		
//		int count = countEmployees(em);
//		println("There are " + count + " employees on file.");
		
//		int pagesize = 25;
//		pagingEmployees(em, pagesize, 0);
				
		findEmployeeByQuery(em, 10001);
	}

	protected void persistEmployee(EntityManager em, Employee employee) {
		int maxEmpNo = maxEmployeesNo(em);
		employee.setEmpNo(maxEmpNo + 1);
		em.persist(employee);
		println("Employee saved. empNo=" + employee.getEmpNo());
		
		println("Search found: " + findEmployeeByQuery(em, employee.getEmpNo()));
	}

	protected Employee findEmployeeByQuery(EntityManager em, int empNo) {
		Employee e = (Employee)em.createQuery("select e from Employee e where e.empNo = :empNo")
			.setParameter("empNo", empNo)
			.getSingleResult();
		return e;
	}

	protected Employee findEmployee(EntityManager em, int empNo) {
		Employee e = (Employee)em.find(Employee.class, empNo);
		return e;
	}

	protected Employee createEmployee() {
		Employee e = new Employee();
		e.setEmpNo((int)System.currentTimeMillis());
		e.setFirstName("One");
		e.setLastName("Tester");
		e.setGender("M");
		e.setBirthDate(new Date(0));
		e.setHireDate(new Date());
		return e;
	}

	protected void pagingEmployees(EntityManager em, int pageSize, int offset) {
		List<?> resultList = em.createQuery("select e from Employee e")
			.setMaxResults(pageSize)
			.setFirstResult(offset)
			.getResultList();
		println("resultList.size=" + resultList.size());		
	}

	protected int countEmployees(EntityManager em) {
		Object result = em.createQuery("select count(e) from Employee e").getSingleResult();
		//println(result.getClass() + ", val=" + result);
		return ((Long)result).intValue();
	}
	
	protected int maxEmployeesNo(EntityManager em) {
		Object result = em.createQuery("select max(e.empNo) from Employee e").getSingleResult();
		return ((Integer)result).intValue();
	}
}
